package org.gdstash.db;

import org.gdstash.file.ARZRecord;
import org.gdstash.util.GDMsgFormatter;
import org.gdstash.util.GDMsgLogger;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

public class DBMerchantTableSet {
    private static final String TABLE_NAME = "GDC_MERCHANTTABLESET";
    private static final int ROW_TABLESET_ID = 1;
    private String tableSetID;
    private List<String> tableIDs;

    public DBMerchantTableSet() {
        this.tableIDs = new LinkedList<String>();
    }

    private DBMerchantTableSet(final ARZRecord record) {
        this.tableSetID = record.getFileName();
        this.tableIDs = record.getMerchantTableIDList();
    }

    public String getMerchantTableSetID() {
        return this.tableSetID;
    }

    public List<String> getTableIDList() {
        return this.tableIDs;
    }

    public static void createTables() throws SQLException {
        final String dropTable = "DROP TABLE GDC_MERCHANTTABLESET";
        final String createTable = "CREATE TABLE GDC_MERCHANTTABLESET (TABLESET_ID       VARCHAR(256) NOT NULL, PRIMARY KEY (TABLESET_ID))";
        try (final Connection conn = GDDBData.getConnection()) {
            final boolean auto = conn.getAutoCommit();
            conn.setAutoCommit(false);
            try (final Statement st = conn.createStatement()) {
                if (GDDBUtil.tableExists(conn, "GDC_MERCHANTTABLESET")) {
                    st.execute(dropTable);
                }
                st.execute(createTable);
                st.close();
                conn.commit();
            } catch (SQLException ex) {
                conn.rollback();
                final Object[] args = {"GDC_MERCHANTTABLESET"};
                final String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_CREATE_TABLE", args);
                GDMsgLogger.addError(msg);
                throw ex;
            } finally {
                conn.setAutoCommit(auto);
            }
        }
        DBMerchantTableSetAlloc.createTable();
    }

    public static void delete(final String tableSetID) throws SQLException {
        final String deleteEntry = "DELETE FROM GDC_MERCHANTTABLESET WHERE TABLE_ID = ?";
        try (final Connection conn = GDDBData.getConnection()) {
            final boolean auto = conn.getAutoCommit();
            conn.setAutoCommit(false);
            try (final PreparedStatement ps = conn.prepareStatement(deleteEntry)) {
                ps.setString(1, tableSetID);
                ps.executeUpdate();
                ps.close();
                DBMerchantTableSetAlloc.delete(conn, tableSetID);
                conn.commit();
            } catch (SQLException ex) {
                conn.rollback();
                final Object[] args = {tableSetID, "GDC_MERCHANTTABLESET"};
                final String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_DEL_TABLE_BY_ID", args);
                GDMsgLogger.addError(msg);
                GDMsgLogger.addError(ex);
                throw ex;
            } finally {
                conn.setAutoCommit(auto);
            }
        } catch (SQLException ex2) {
            throw ex2;
        }
    }

    public static void insert(final ARZRecord record) throws SQLException {
        final DBMerchantTableSet entry = get(record.getFileName());
        if (entry != null) {
            return;
        }
        final DBMerchantTableSet merchantTableSet = new DBMerchantTableSet(record);
        if (merchantTableSet.tableIDs == null) {
            return;
        }
        if (merchantTableSet.tableIDs.isEmpty()) {
            return;
        }
        final String insert = "INSERT INTO GDC_MERCHANTTABLESET VALUES (?)";
        try (final Connection conn = GDDBData.getConnection()) {
            final boolean auto = conn.getAutoCommit();
            conn.setAutoCommit(false);
            try (final PreparedStatement ps = conn.prepareStatement(insert)) {
                ps.setString(1, merchantTableSet.tableSetID);
                ps.executeUpdate();
                ps.close();
                conn.commit();
                DBMerchantTableSetAlloc.insert(conn, merchantTableSet);
            } catch (SQLException ex) {
                conn.rollback();
                final Object[] args = {record.getFileName(), "GDC_MERCHANTTABLESET"};
                final String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_INS_TABLE_BY_ID", args);
                GDMsgLogger.addLowError(msg);
                GDMsgLogger.addLowError(ex);
            } finally {
                conn.setAutoCommit(auto);
            }
        }
    }

    public static DBMerchantTableSet get(final String tableSetID) {
        DBMerchantTableSet tableSet = new DBMerchantTableSet();
        final String command = "SELECT * FROM GDC_MERCHANTTABLESET WHERE TABLESET_ID = ?";
        try (final Connection conn = GDDBData.getConnection();
             final PreparedStatement ps = conn.prepareStatement(command)) {
            ps.setString(1, tableSetID);
            try (final ResultSet rs = ps.executeQuery()) {
                final List<DBMerchantTableSet> list = wrap(rs);
                if (list.isEmpty()) {
                    tableSet = null;
                } else {
                    tableSet = list.get(0);
                }
                conn.commit();
            } catch (SQLException ex) {
                throw ex;
            }
        } catch (SQLException ex2) {
            final Object[] args = {tableSetID, "GDC_MERCHANTTABLESET"};
            final String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_READ_TABLE_BY_ID", args);
            GDMsgLogger.addError(msg);
            GDMsgLogger.addError(ex2);
        }
        return tableSet;
    }

    private static List<DBMerchantTableSet> wrap(final ResultSet rs) throws SQLException {
        final LinkedList<DBMerchantTableSet> list = new LinkedList<DBMerchantTableSet>();
        while (rs.next()) {
            final DBMerchantTableSet tableSet = new DBMerchantTableSet();
            tableSet.tableSetID = rs.getString(1);
            tableSet.tableIDs = DBMerchantTableSetAlloc.getByMerchantTableSetID(tableSet.tableSetID);
            list.add(tableSet);
        }
        return list;
    }
}
